import Vue from 'vue'
import Router from 'vue-router'
import store from '@/store.js'
// =========================实现路由的懒加载，打包时更加优化
const Layout = () => import('@/views/layout')
const Home = () => import('@/views/home/index')
const Detail = () => import('@/views/home/detail')
const Question = () => import('@/views/question/index')
const Video = () => import('@/views/video/index')
const User = () => import('@/views/user/index')
const Profile = () => import('@/views/user/profile')
const Search = () => import('@/views/search/index')
const Chat = () => import('@/views/user/chat')
const Login = () => import('@/views/user/login')
const Result = () => import('@/views/search/result')
Vue.use(Router)

const router = new Router({
  routes: [{
    path: '/',
    component: Layout,
    children: [{
      path: '/',
      name: 'home',
      component: Home,
      meta: { keepAlive: true }
    }, {
      path: '/question',
      name: 'question',
      component: Question
    },

    {
      path: '/video',
      name: 'video',
      component: Video
    },

    {
      path: '/user',
      name: 'user',
      component: User
    }
    ]
  }, {
    path: '/home/detail',
    name: 'detail',
    component: Detail,
    meta: { keepAlive: true }

  }, {
    path: '/user/profile',
    name: 'profile',
    component: Profile
  }, {
    path: '/login',
    name: 'login',
    component: Login
  }, {
    path: '/user/chat',
    name: 'chat',
    component: Chat
  }, {
    path: '/search',
    name: 'search',
    component: Search
  }, {
    path: '/search/result',
    name: 'result',
    component: Result
  }

  ]
})
router.beforeEach((to, from, next) => {
  // 跳转的时候需要 带上当前的路由地址
  const login = { path: '/login', query: { redirect: to.path } }
  if (to.path.startsWith('/user') && !store.state.auth.token) return next(login)
  next()
})
export default router
// ==============这里声明变量的原因是，如果直接导出实例无法在加路由守卫
